"""
spark写入的记录给前端展示
"""
from flask import request, jsonify

from apps.apis import api
from apps.core.auth import verify_json_schema, verify_token_auth
from apps.core.schemaall import token_schema, subdbid_schema, subdbid_year_schema
from apps.models import UpdateMeta, SubDb, CountSubdbYearMeta, UpdateRef, CountSubDbYearRef
from apps.utils.return_info import ReturnInfo
from apps.utils.tools import mzfill


# @api.route("/stat/update_ref", methods=['POST'])
# @verify_json_schema(token_schema)
# @verify_token_auth(allowtokennull=True)
def update_ref_record():
    """
    引文 统计数据 的记录 查询每个字库的最新一条数据
    ---
    tags:
      - stat
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
    definitions:
      UpdateRef:
        type: object
        properties:
          sub_db_name:
            type: string
            description: 为每个字库分配的id
            example: 维普期刊
          sub_db_id:
            type: string
            description: 为每个字库分配的id
            example: '00001'
          count_submit:
            type: integer
            description: 提交量.
            example: 10
          count_update:
            type: integer
            description: 更新量.
            example: 8
          count_create:
            type: integer
            description: 新增量.
            example: 8
          count_deprecated:
            type: integer
            description: 弃用量.
            example: 6
          count_delete:
            type: integer
            description: 物理删除量.
            example: 6
          count_ref:
            type: integer
            description: 更新后总量.
            example: 6
      ReturnInfoUpdateRef:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: object
            description: 所有字段信息和总条数
            properties:
              result:
                properties:
                  total:
                    type: integer
                    description: 总条数
                    example: 126
                  querydata:
                    type: integer
                    description: 数据列表,如果超出总条数返回为空列表
                    items:
                      $ref: '#/definitions/UpdateRef'
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoUpdateRef'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"成功","data":[]}
      400:
        description: 上传数据有不符合规则,data中放入的是上传的数据.
        examples:
          returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
      401:
        description: token 认证不通过,可能是过期
      405:
        description: 请求方式错误
    :return:
    """
    ret_obj = ReturnInfo()

    subDbAll = SubDb.query.with_entities(SubDb.sub_db_id, SubDb.sub_db_name).all()
    listdata = []
    for subDb in subDbAll:
        sub_db_id = mzfill(subDb.sub_db_id)
        sub_db_name = subDb.sub_db_name
        updateRef = UpdateRef.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateRef.update_time.desc()).first()
        if updateRef:
            updaterefdicts = {}
            updaterefdicts["sub_db_name"] = sub_db_name
            updaterefdicts["sub_db_id"] = updateRef.sub_db_id
            updaterefdicts["count_submit"] = updateRef.count_submit
            updaterefdicts["count_update"] = updateRef.count_update
            updaterefdicts["count_create"] = updateRef.count_create
            updaterefdicts["count_deprecated"] = updateRef.count_deprecated
            updaterefdicts["count_delete"] = updateRef.count_delete
            updaterefdicts["count_ref"] = updateRef.count_ref
            listdata.append(updaterefdicts)

    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "成功"
    ret_obj.data = listdata
    return jsonify(ret_obj.todict())


@api.route("/stat/update_ref_subdbid", methods=['POST'])
@verify_json_schema(subdbid_schema)
@verify_token_auth(allowtokennull=True)
def update_ref_subdbid():
    """
    引文 统计数据 的记录 查询某个字库的全部数据
    ---
    tags:
      - stat
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
            sub_db_id:
              type: string
              description: 为每个字库分配的id
              example: '00001'
    definitions:
      UpdateRef:
        type: object
        properties:
          sub_db_name:
            type: string
            description: 为每个字库分配的id
            example: 维普期刊
          sub_db_id:
            type: string
            description: 为每个字库分配的id
            example: '00001'
          count_submit:
            type: integer
            description: 提交量.
            example: 10
          count_update:
            type: integer
            description: 更新量.
            example: 8
          count_create:
            type: integer
            description: 新增量.
            example: 8
          count_deprecated:
            type: integer
            description: 弃用量.
            example: 6
          count_delete:
            type: integer
            description: 物理删除量.
            example: 6
          count_ref:
            type: integer
            description: 更新后总量.
            example: 6
          update_time:
            type: string
            description: 更新时间
            example: '2019-11-23 08:27:57'
      ReturnInfoUpdateRef:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: object
            description: 所有字段信息和总条数
            properties:
              result:
                properties:
                  total:
                    type: integer
                    description: 总条数
                    example: 126
                  querydata:
                    type: integer
                    description: 数据列表,如果超出总条数返回为空列表
                    items:
                      $ref: '#/definitions/UpdateRef'
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoUpdateRef'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"成功","data":[]}
      400:
        description: 上传数据有不符合规则,data中放入的是上传的数据.
        examples:
          returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
      401:
        description: token 认证不通过,可能是过期
      405:
        description: 请求方式错误
    :return:
    """
    ret_obj = ReturnInfo()
    jsons = request.json
    sub_db_id = jsons.get("sub_db_id")
    sub_db_name = jsons.get("sub_db_name")
    listdata = []
    updateRefAll = UpdateRef.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateRef.update_time.asc()).all()
    for updateRef in updateRefAll:
        updaterefdicts = {}
        updaterefdicts["sub_db_name"] = sub_db_name
        updaterefdicts["sub_db_id"] = updateRef.sub_db_id
        updaterefdicts["count_submit"] = updateRef.count_submit
        updaterefdicts["count_update"] = updateRef.count_update
        updaterefdicts["count_create"] = updateRef.count_create
        updaterefdicts["count_deprecated"] = updateRef.count_deprecated
        updaterefdicts["count_delete"] = updateRef.count_delete
        updaterefdicts["count_ref"] = updateRef.count_ref
        updaterefdicts["update_time"] = str(updateRef.update_time)
        listdata.append(updaterefdicts)

    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "成功"
    ret_obj.data = listdata
    return jsonify(ret_obj.todict())


@api.route("/stat/count_subdb_year_ref", methods=['POST'])
@verify_json_schema(subdbid_year_schema)
@verify_token_auth(allowtokennull=True)
def stat_count_subdb_year_ref():
    """
    引文 用 sub_db_id+years 查询 count_subdb_year_ref 表，取该年所有记录
    ---
    tags:
      - stat
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
            sub_db_id:
              type: string
              description: 为每个字库分配的id
              example: '00001'
            year:
              type: string
              description: 年
              example: '2018'
    definitions:
      CountSubdbYear:
        type: object
        properties:
          sub_db_id:
            type: string
            description: 为每个字库分配的id
            example: '00001'
          count_json:
            type: object
            description: 不同结构的json数据
            example: {"aa":"bb","cc":"dd"}
      ReturnInfoCountSubdbYear:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: object
            description: 所有字段信息和总条数
            properties:
              result:
                properties:
                  total:
                    type: integer
                    description: 总条数
                    example: 126
                  querydata:
                    type: integer
                    description: 数据列表,如果超出总条数返回为空列表
                    items:
                      $ref: '#/definitions/CountSubdbYear'
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoCountSubdbYear'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"更新数据成功","data":[]}
      400:
        description: 上传数据有不符合规则,data中放入的是上传的数据.
        examples:
          returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
      401:
        description: token 认证不通过,可能是过期
      405:
        description: 请求方式错误
    :return:
    """
    ret_obj = ReturnInfo()
    jsons = request.json
    sub_db_id = jsons.get("sub_db_id")
    year = jsons.get("year")
    subDb = SubDb.query.filter_by(sub_db_id=sub_db_id).first()
    sub_db_name = subDb.sub_db_name
    CountSubdbYearAll = CountSubDbYearRef.query.filter_by(sub_db_id=sub_db_id).order_by(
        CountSubDbYearRef.id.asc()).all()
    listdata = []
    for countSubdbYear in CountSubdbYearAll:
        dicts = {}
        count_json = countSubdbYear.count_json
        update_time = str(countSubdbYear.update_time)
        dicts["update_time"] = update_time
        for items in count_json.get("msg"):
            if items.get("cited_pub_year") == year:
                dicts["msg"] = items
        listdata.append(dicts)

    ret_obj.data = listdata
    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "成功"
    return jsonify(ret_obj.todict())


@api.route("/stat/count_subdb_new_ref", methods=['POST'])
@verify_json_schema(subdbid_schema)
@verify_token_auth(allowtokennull=True)
def count_subdb_new_ref():
    """
    引文 用 sub_db_id 查询 count_subdb_year_ref，取最新记录
    里面包含年份统计数据
    ---
    tags:
      - stat
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
            sub_db_id:
              type: string
              description: 为每个字库分配的id
              example: '00001'
    definitions:
      CountSubdbYear:
        type: object
        properties:
          sub_db_id:
            type: string
            description: 为每个字库分配的id
            example: '00001'
          count_json:
            type: object
            description: 不同结构的json数据
            example: {"aa":"bb","cc":"dd"}
      ReturnInfoCountSubdbYear:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: object
            description: 所有字段信息和总条数
            properties:
              result:
                properties:
                  total:
                    type: integer
                    description: 总条数
                    example: 126
                  querydata:
                    type: integer
                    description: 数据列表,如果超出总条数返回为空列表
                    items:
                      $ref: '#/definitions/CountSubdbYear'
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoCountSubdbYear'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"更新数据成功","data":[]}
      400:
        description: 上传数据有不符合规则,data中放入的是上传的数据.
        examples:
          returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
      401:
        description: token 认证不通过,可能是过期
      405:
        description: 请求方式错误
    :return:
    """
    ret_obj = ReturnInfo()
    jsons = request.json
    sub_db_id = jsons.get("sub_db_id")
    subDb = SubDb.query.filter_by(sub_db_id=sub_db_id).first()
    sub_db_name = subDb.sub_db_name
    countSubdbYear = CountSubDbYearRef.query.filter_by(sub_db_id=sub_db_id).order_by(
        CountSubDbYearRef.id.desc()).first()
    logsysdicts = {}
    if countSubdbYear:
        logsysdicts["update_time"] = str(countSubdbYear.update_time)
        logsysdicts["msg"] = countSubdbYear.count_json["msg"]

    ret_obj.data = {"result": logsysdicts}
    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "成功"
    return jsonify(ret_obj.todict())


@api.route("/stat/update_meta", methods=['POST'])
@verify_json_schema(token_schema)
@verify_token_auth(allowtokennull=True)
def update_meta_record():
    """
     题录 统计数据 的所有记录
    ---
    tags:
      - stat
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
    definitions:
      UpdateMeta:
        type: object
        properties:
          sub_db_name:
            type: string
            description: 为每个字库分配的id
            example: 维普期刊
          sub_db_id:
            type: string
            description: 为每个字库分配的id
            example: '00001'
          count_submit:
            type: integer
            description: 提交量.
            example: 10
          count_update:
            type: integer
            description: 更新量.
            example: 8
          count_create:
            type: integer
            description: 新增量.
            example: 8
          count_deprecated:
            type: integer
            description: 弃用量.
            example: 6
          count_delete:
            type: integer
            description: 物理删除量.
            example: 6
          count_meta:
            type: integer
            description: 更新后总量.
            example: 6
      ReturnInfoUpdateMeta:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: object
            description: 所有字段信息和总条数
            properties:
              result:
                properties:
                  total:
                    type: integer
                    description: 总条数
                    example: 126
                  querydata:
                    type: integer
                    description: 数据列表,如果超出总条数返回为空列表
                    items:
                      $ref: '#/definitions/UpdateMeta'
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoUpdateMeta'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"成功","data":[]}
      400:
        description: 上传数据有不符合规则,data中放入的是上传的数据.
        examples:
          returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
      401:
        description: token 认证不通过,可能是过期
      405:
        description: 请求方式错误
    :return:
    """
    ret_obj = ReturnInfo()
    subDbAll = SubDb.query.with_entities(SubDb.sub_db_id, SubDb.sub_db_name).all()
    listdata = []
    for subDb in subDbAll:
        sub_db_id = mzfill(subDb.sub_db_id)
        sub_db_name = subDb.sub_db_name
        updateMeta = UpdateMeta.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateMeta.update_time.desc()).first()
        if updateMeta:
            updatemetadicts = {}
            updatemetadicts["sub_db_name"] = sub_db_name
            updatemetadicts["sub_db_id"] = updateMeta.sub_db_id
            updatemetadicts["count_submit"] = updateMeta.count_submit
            updatemetadicts["count_update"] = updateMeta.count_update
            updatemetadicts["count_create"] = updateMeta.count_create
            updatemetadicts["count_deprecated"] = updateMeta.count_deprecated
            updatemetadicts["count_delete"] = updateMeta.count_delete
            updatemetadicts["count_meta"] = updateMeta.count_meta
            listdata.append(updatemetadicts)

    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "成功"
    ret_obj.data = listdata
    return jsonify(ret_obj.todict())


@api.route("/stat/update_meta_subdbid", methods=['POST'])
@verify_json_schema(subdbid_schema)
# @verify_token_auth(allowtokennull=True)
def update_meta_subdbid():
    """
    题录 统计数据 的记录 查询某个子库的全部数据
    ---
    tags:
      - stat
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
            sub_db_id:
              type: string
              description: 为每个字库分配的id
              example: '00001'
    definitions:
      UpdateRef:
        type: object
        properties:
          sub_db_name:
            type: string
            description: 为每个字库分配的id
            example: 维普期刊
          sub_db_id:
            type: string
            description: 为每个字库分配的id
            example: '00001'
          count_submit:
            type: integer
            description: 提交量.
            example: 10
          count_update:
            type: integer
            description: 更新量.
            example: 8
          count_create:
            type: integer
            description: 新增量.
            example: 8
          count_deprecated:
            type: integer
            description: 弃用量.
            example: 6
          count_delete:
            type: integer
            description: 物理删除量.
            example: 6
          count_meta:
            type: integer
            description: 更新后总量.
            example: 6
          update_time:
            type: string
            description: 更新时间
            example: '2019-11-23 08:27:57'
      ReturnInfoUpdateMeta:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: object
            description: 所有字段信息和总条数
            properties:
              result:
                properties:
                  total:
                    type: integer
                    description: 总条数
                    example: 126
                  querydata:
                    type: integer
                    description: 数据列表,如果超出总条数返回为空列表
                    items:
                      $ref: '#/definitions/UpdateMeta'
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoUpdateMeta'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"成功","data":[]}
      400:
        description: 上传数据有不符合规则,data中放入的是上传的数据.
        examples:
          returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
      401:
        description: token 认证不通过,可能是过期
      405:
        description: 请求方式错误
    :return:
    """
    ret_obj = ReturnInfo()
    jsons = request.json
    sub_db_id = jsons.get("sub_db_id")
    subDb = SubDb.query.filter_by(sub_db_id=sub_db_id).first()
    sub_db_name = subDb.sub_db_name
    listdata = []
    UpdateMetaAll = UpdateMeta.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateMeta.update_time.asc()).all()
    for updateMeta in UpdateMetaAll:
        updatemetadicts = {}
        updatemetadicts["sub_db_name"] = sub_db_name
        updatemetadicts["sub_db_id"] = updateMeta.sub_db_id
        updatemetadicts["count_submit"] = updateMeta.count_submit
        updatemetadicts["count_update"] = updateMeta.count_update
        updatemetadicts["count_create"] = updateMeta.count_create
        updatemetadicts["count_deprecated"] = updateMeta.count_deprecated
        updatemetadicts["count_delete"] = updateMeta.count_delete
        updatemetadicts["count_meta"] = updateMeta.count_meta
        updatemetadicts["update_time"] = str(updateMeta.update_time)
        listdata.append(updatemetadicts)

    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "成功"
    ret_obj.data = listdata
    return jsonify(ret_obj.todict())


# @api.route("/stat/logsys", methods=['POST'])
# @verify_json_schema(paging_schema)
# @verify_token_auth(allowtokennull=True)
# def logsys_record():
#     """
#     spark系统运行日志 的记录
#     ---
#     tags:
#       - stat
#     parameters:
#       - in: body
#         name: body
#         required: true
#         description: JSON 参数.
#         schema:
#           properties:
#             token:
#               type: string
#               description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
#               example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
#             page:
#               type: integer
#               description: 页码，后台会自动减1再乘以size当作开始的位置
#               example: 1
#             size:
#               type: integer
#               description: 最大后台限制 1000条数据
#               example: 1000
#     definitions:
#       LogSys:
#         type: object
#         properties:
#           log_json:
#             type: object
#             description: json结构的日志
#             example: {"aa":"bb","cc":"dd"}
#       ReturnInfoLogSys:
#         type: object
#         properties:
#           msg_code:
#             type: string
#             description: SUCCESS 或者 FAILED.
#             example: SUCCESS
#           msg:
#             type: string
#             description: 说明文字，帮助找到失败原因
#             example: 不能使用get请求
#           data:
#             type: object
#             description: 所有字段信息和总条数
#             properties:
#               result:
#                 properties:
#                   total:
#                     type: integer
#                     description: 总条数
#                     example: 126
#                   querydata:
#                     type: integer
#                     description: 数据列表,如果超出总条数返回为空列表
#                     items:
#                       $ref: '#/definitions/LogSys'
#     consumes:
#       - application/json
#     produces:
#       - application/json
#
#     responses:
#       200:
#         description: OK.
#         schema:
#           $ref: '#/definitions/ReturnInfoLogSys'
#         examples:
#           returninfo: {"msg_code":"SUCCESS","msg":"更新数据成功","data":[]}
#       400:
#         description: 上传数据有不符合规则,data中放入的是上传的数据.
#         examples:
#           returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
#       401:
#         description: token 认证不通过,可能是过期
#       405:
#         description: 请求方式错误
#     :return:
#     """
#     ret_obj = ReturnInfo()
#     jsons = request.json
#     page = jsons.get("page")
#     size = jsons.get("size")
#     pagination = LogSys.query.order_by(
#         LogSys.id.desc()).paginate(page, per_page=size, max_per_page=1000, error_out=True)
#     count = pagination.total
#     logSysAll = pagination.items
#     listdata = []
#     logsysdicts = {}
#     for logSys in logSysAll:
#         logsysdicts["log_json"] = logSys.log_json
#         listdata.append(logsysdicts)
#     ret_obj.msg_code = "SUCCESS"
#     ret_obj.msg = "成功"
#     ret_obj.data = {"result": {"querydata": listdata, "total": count}}
#     return jsonify(ret_obj.todict())


@api.route("/stat/count_subdb_year", methods=['POST'])
@verify_json_schema(subdbid_year_schema)
@verify_token_auth(allowtokennull=True)
def count_subdb_year_record():
    """
    用 sub_db_id+years 查询 count_subdb_year_meta 表，取该年所有记录
    ---
    tags:
      - stat
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
            sub_db_id:
              type: string
              description: 为每个字库分配的id
              example: '00001'
            year:
              type: string
              description: 年
              example: '2018'
    definitions:
      CountSubdbYear:
        type: object
        properties:
          sub_db_id:
            type: string
            description: 为每个字库分配的id
            example: '00001'
          count_json:
            type: object
            description: 不同结构的json数据
            example: {"aa":"bb","cc":"dd"}
      ReturnInfoCountSubdbYear:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: object
            description: 所有字段信息和总条数
            properties:
              result:
                properties:
                  total:
                    type: integer
                    description: 总条数
                    example: 126
                  querydata:
                    type: integer
                    description: 数据列表,如果超出总条数返回为空列表
                    items:
                      $ref: '#/definitions/CountSubdbYear'
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoCountSubdbYear'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"更新数据成功","data":[]}
      400:
        description: 上传数据有不符合规则,data中放入的是上传的数据.
        examples:
          returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
      401:
        description: token 认证不通过,可能是过期
      405:
        description: 请求方式错误
    :return:
    """
    ret_obj = ReturnInfo()
    jsons = request.json
    sub_db_id = jsons.get("sub_db_id")
    year = jsons.get("year")
    subDb = SubDb.query.filter_by(sub_db_id=sub_db_id).first()
    sub_db_name = subDb.sub_db_name
    CountSubdbYearAll = CountSubdbYearMeta.query.filter_by(sub_db_id=sub_db_id).order_by(
        CountSubdbYearMeta.id.asc()).all()
    listdata = []
    for countSubdbYear in CountSubdbYearAll:
        dicts = {}
        count_json = countSubdbYear.count_json
        update_time = str(countSubdbYear.update_time)
        dicts["update_time"] = update_time
        for items in count_json.get("msg"):
            if items.get("pub_year") == year:
                dicts["msg"] = items
        listdata.append(dicts)

    ret_obj.data = listdata
    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "成功"
    return jsonify(ret_obj.todict())


@api.route("/stat/count_subdb_new", methods=['POST'])
@verify_json_schema(subdbid_schema)
@verify_token_auth(allowtokennull=True)
def count_subdb_new():
    """
    用 sub_db_id 查询 count_subdb_year，取最新一条记录,
    里面包含年份统计数据
    ---
    tags:
      - stat
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: token. 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Mjg0NzY3OSwiZXhwIjoxNTcyODQ4Mjc5fQ.eyJpZCI6MX0.rLbJ_6UQHuHoEA2xjbqtUa28Ogtf2I4JEDa0En0WjgB5pe5L1gT6F5L0RktZuJBE1lBEGT0TAJ1YC7PddwE-Cg
            sub_db_id:
              type: string
              description: 为每个字库分配的id
              example: '00001'
    definitions:
      CountSubdbYear:
        type: object
        properties:
          sub_db_id:
            type: string
            description: 为每个字库分配的id
            example: '00001'
          count_json:
            type: object
            description: 不同结构的json数据
            example: {"aa":"bb","cc":"dd"}
      ReturnInfoCountSubdbYear:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: object
            description: 所有字段信息和总条数
            properties:
              result:
                properties:
                  total:
                    type: integer
                    description: 总条数
                    example: 126
                  querydata:
                    type: integer
                    description: 数据列表,如果超出总条数返回为空列表
                    items:
                      $ref: '#/definitions/CountSubdbYear'
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoCountSubdbYear'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"更新数据成功","data":[]}
      400:
        description: 上传数据有不符合规则,data中放入的是上传的数据.
        examples:
          returninfo: {"msg_code":"FAILED","msg":"上传格式错误","data":{"result":"这里放入上传的json"}}
      401:
        description: token 认证不通过,可能是过期
      405:
        description: 请求方式错误
    :return:
    """
    ret_obj = ReturnInfo()
    jsons = request.json
    sub_db_id = jsons.get("sub_db_id")
    subDb = SubDb.query.filter_by(sub_db_id=sub_db_id).first()
    sub_db_name = subDb.sub_db_name
    countSubdbYear = CountSubdbYearMeta.query.filter_by(sub_db_id=sub_db_id).order_by(
        CountSubdbYearMeta.id.desc()).first()
    logsysdicts = {}
    if countSubdbYear:
        logsysdicts["update_time"] = str(countSubdbYear.update_time)
        logsysdicts["msg"] = countSubdbYear.count_json["msg"]

    ret_obj.data = {"result": logsysdicts}
    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "成功"
    return jsonify(ret_obj.todict())
